#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/bk/apis/job/gse_proc_operate.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
from django import forms
from common.forms import BaseComponentForm, TypeCheckField
from common.constants import API_TYPE_OP
from components.component import Component
from .toolkit import tools, configs

class GseProcOperate(Component):
    """
    apiLabel 进程操作
    apiMethod POST
    
    ### 功能描述
    
    进程操作
    
    ### 请求参数
    
    {{ common_args_desc }}
    
    #### 接口参数
    
    | 字段        |  类型      | 必选   |  描述      |
    |-------------|------------|--------|------------|
    | app_id      |  int       | 是     | 业务ID |
    | operate_type|  int       | 是     | 操作类型，可选值：0:启动进程(start); 1:停止进程(stop); 2:进程状态查询; 3:注册托管进程; 4:取消托管进程; 7:重启进程(restart); 8:重新加载进程(reload); 9:杀死进程(kill) |
    | proc_list   |  array     | 是     | 待操作进程信息 |
    
    #### proc_list
    
    | 字段        |  类型      | 必选   |  描述      |
    |-------------|------------|--------|------------|
    | ip_list     |  array     | 是     | IP 列表 |
    | setup_path  |  string    | 是     | 进程路径，例如/usr/local/gse/gseagent/plugins/unifyTlogc/sbin |
    | proc_name   |  string    | 是     | 进程名称，例如bk_gse_unifyTlogc |
    | pid_path    |  string    | 是     | pid文件所在路径, 例如/usr/local/gse/gseagent/plugins/unifyTlogc/log/bk_gse_unifyTlogc.pid |
    | username    |  string    | 否     | 系统用户名，不传默认为root |
    
    #### ip_list
    
    | 字段        |  类型      | 必选   |  描述      |
    |-------------|------------|--------|------------|
    | ip          |  string    | 是     | IP 地址 |
    | source      |  int       | 是     | 子网ID |
    
    ### 请求参数示例
    
    ```python
    {
        "app_code": "esb_test",
        "app_secret": "xxx",
        "bk_token": "xxx",
        "username": "admin",
        "app_id": 46,
        "operate_type": 1,
        "proc_list": [
            {
                "ip_list": [
                    {
                        "ip": "10.0.0.1",
                        "source": 1,
                    }
                ],
                "setup_path": "/usr/local/gse/gseagent/plugins/unifyTlogc/sbin",
                "proc_name": "bk_gse_unifyTlogc",
                "pid_path": "/usr/local/gse/gseagent/plugins/unifyTlogc/log/bk_gse_unifyTlogc",
                "username": "root"
            }
        ]
    }
    ```
    
    ### 返回结果示例
    
    ```python
    {
        "result": true,
        "code": "00",
        "message": "",
        "data": {
            "errorCode": 0,
            "gseTaskId": "GSETASK:20170413215154:8239",
            "errorMessage": "success"
        },
    }
    ```
    """
    sys_name = configs.SYSTEM_NAME
    api_type = API_TYPE_OP
    host = configs.host

    class Form(BaseComponentForm):
        app_id = forms.IntegerField(label=u'业务ID', required=True)
        operate_type = forms.IntegerField(label=u'操作类型', required=True)
        proc_list = TypeCheckField(label=u'待操作进程信息', promise_type=list, required=True)

        def clean(self):
            data = self.cleaned_data
            return {'applicationId': data['app_id'],
               'operType': data['operate_type'],
               'processInfos': [ GseProcOperate.ProcForm(proc).get_cleaned_data_or_error() for proc in data['proc_list']
                             ]
               }

    class ProcForm(BaseComponentForm):
        ip_list = TypeCheckField(label=u'IP 列表', promise_type=list, required=True)
        setup_path = forms.CharField(label=u'进程路径', required=True)
        proc_name = forms.CharField(label=u'进程名称', required=True)
        pid_path = forms.CharField(label=u'pid文件所在路径', required=True)
        username = forms.CharField(label=u'系统用户名', required=False)

        def clean(self):
            data = self.cleaned_data
            return {'ipList': [ GseProcOperate.IPForm(ip).get_cleaned_data_or_error() for ip in data['ip_list']
                       ],
               'setupPath': data['setup_path'],
               'procName': data['proc_name'],
               'pidPath': data['pid_path'],
               'userName': data['username']
               }

    class IPForm(BaseComponentForm):
        ip = forms.IPAddressField(label=u'IP 地址', required=True)
        source = forms.IntegerField(label=u'子网ID', required=True)

    def handle(self):
        data = self.form_data
        data['operator'] = self.current_user.username
        client = tools.JOBClient(self.outgoing.http_client)
        params = tools.get_basic_json('gseProcessOperate', params=data)
        result = client.post(self.host, data=params)
        self.response.payload = result
